import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin} from 'antd';
import WrappedDatePicker from '../common/WrappedDatePicker';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions, createValidator} from './utils';
import {PERMISSION} from './constants';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
export class CreatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {}
    };
    componentWillUnmount() {
        this.isunmount = true;
    }

    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onSubmit = () => {
        const isValid = createValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    render() {
        const data = this.state.data;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateBeginDate = !data.beginDate && this.state.validate ? 'error' : null;
        const validateEndDate = !data.endDate && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission, initEnum} = this.props;
        const submitable = hasPermissions(PERMISSION.create, pagePermission);
        let secomdClaimPeriodsNew = [];
        if(data.brandId)
            secomdClaimPeriodsNew = initEnum.secomdClaimPeriods.filter(v => v.brandId === data.brandId);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'createPanel.card.title',
                            defaultMessage: '汇总生成'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'createPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required >
                                        <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={initEnum.brands}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.beginDate',
                                            defaultMessage: '开始时间'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBeginDate} required >
                                        <WrappedDatePicker
                                            name="beginDate"
                                            disabledDate={this.disabledDate}
                                            value={data.beginDate}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.endDate',
                                            defaultMessage: '结束时间'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateEndDate} required >
                                        <WrappedDatePicker
                                            name="endDate"
                                            disabledDate={this.disabledDate}
                                            value={data.endDate}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                {/* <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'createPanel.form.secomdClaimPeriodId',
                                            defaultMessage: '周期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.brandId ? <WrappedSelect
                                            allowClear
                                            name="secomdClaimPeriodId"
                                            value={data.secomdClaimPeriodId}
                                            options={secomdClaimPeriodsNew}
                                            onChange={this.handleFilterChange} /> : <TextInput name="secomdClaimPeriodId"
                                            value={''} disabled placeholder={this.props.intl.formatMessage({
                                                id: 'createPanel.dealerComp.placeholder',
                                                defaultMessage: '请先选择品牌'
                                            })} />}
                                    </FormItem>
                                </Col> */}
                            </Row>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'createPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

CreatePanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onCreate,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const secomdClaimPeriods = initData.secomdClaimPeriods ? initData.secomdClaimPeriods.map(item => ({
            text: `${'('}${item.code}${')'}${item.startDay} - ${item.endDay}`,
            value: item.id,
            brandId: item.brandId
        })) : [];
        return {
            brands,
            secomdClaimPeriods
        };
    }
);

const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getInitData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onCreate(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url())
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(CreatePanel));
